import React, {Component, useState} from 'react';
import {PlusOutlined} from '@ant-design/icons';
import {Modal, Upload} from 'antd';

const ZOHO = window.ZOHO;
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });

class ImageUpload extends Component {
    constructor(props) {
        super(props);
        console.log(props)
        let url = "";
        let fileList = [];
        if (props.picture !== undefined) {
            url = `https://crm.zoho.com.cn/crm/org41013454/ViewImage?fileId=${props.picture.File_Id}&module=CustomModule10&parentId=${props.id}&name=${props.picture.File_Name}&downLoadMode=inline`;
            fileList = [
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: url,
                }
            ];
        }
        const uploadButton = (
            <div>
                <PlusOutlined/>
                <div
                    style={{
                        marginTop: 8,
                    }}
                >
                    Upload
                </div>
            </div>
        );
        this.state = {
            previewOpen: false,
            previewImage: '',
            fileList: fileList,
            picture: {
                File_Id: "",
                File_Name: "",
            },
            parentId: props.id,
            uploadButton: uploadButton

        }

    }

    handleCancel = () => {
        this.setState({previewOpen: false})
    };
    handlePreview = async (file) => {
        this.setState({
            previewOpen: true,
            previewImage: file.url
        })
    };
    handleUpload = async (file) => {

        const {parentId} = this.state;
        let fileList = [];
        let config = {
            "CONTENT_TYPE": "multipart",
            "PARTS": [{
                "headers": {
                    "Content-Disposition": "file;"
                },
                "content": "__FILE__"
            }],
            "FILE": {
                "fileParam": "content",
                "file": file
            }
        }
        try {
            const response = await ZOHO.CRM.API.uploadFile(config);
            console.log(response);
            const detail = response.data[0].details;
            this.setState({picture: {Encrypted_Id: detail.id}})
            return Promise.resolve(await getBase64(file)); // 使用 Promise.resolve() 返回解析的 Promise 对象
        } catch (error) {
            console.error(error);
            return Promise.reject(error); // 使用 Promise.reject() 返回拒绝的 Promise 对象

        }
    }

    handleChange = ({fileList: newFileList}) => {
        let {picture} = this.state;
        if (newFileList.length === 0) {
            picture = {
                desc: "delete"
            }
        } else {
            picture.desc = "add";
        }
        console.log(picture)
        this.props.onChange(picture)

        this.setState({
            fileList: newFileList
        })


    };

    handleBeforeUpload = (newFileList) => {
        this.setState({
            fileList: [{
                uid: newFileList.uid,
                name: newFileList.name,
                status: 'uploading',
                url: '',
            }]
        })
    }


    render() {
        const {fileList, uploadButton, previewOpen, previewImage} = this.state;
        return (
            <>
                <Upload
                    action={this.handleUpload}
                    listType="picture-card"
                    fileList={fileList}
                    accept="image/*"
                    beforeUpload={this.handleBeforeUpload}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <Modal open={previewOpen} onCancel={this.handleCancel}>
                    <img
                        alt="example"
                        style={{
                            width: '100%',
                        }}
                        src={previewImage}
                    />
                </Modal>
            </>
        );
    }


}

export default ImageUpload;